<template>
  <div class="app-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="granularity">
          <el-radio-group v-model="granularity">
            <el-radio-button label="day">日</el-radio-button>
            <el-radio-button label="month">月</el-radio-button>
            <el-radio-button label="year">年</el-radio-button>
          </el-radio-group>
        </div>

        <div class="date-picker">
          <el-date-picker
            v-model="pickedDate"
            :type="datePickerType"
            :format="dateFormat"
            :value-format="valueFormat"
            placeholder="日期筛选"
            style="width: 180px"
          />
        </div>

        <div class="energy-type">
          <el-select
            v-model="energyType"
            placeholder="能源类型"
            style="width: 120px"
          >
            <el-option label="电" :value="20" />
            <el-option label="水" :value="10" />
            <el-option label="气" :value="30" />
            <el-option label="热" :value="40" />
          </el-select>
        </div>

        <el-button type="primary" icon="Search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="kpi-section">
      <el-card class="kpi-card">
        <div class="kpi-title">累计能耗</div>
        <div class="kpi-value">{{ totalEnergy }} kWh</div>
      </el-card>
      <el-card class="kpi-card">
        <div class="kpi-title">分表能耗</div>
        <div class="kpi-value">{{ subEnergy }} kWh</div>
      </el-card>
      <el-card class="kpi-card">
        <div class="kpi-title">损失量</div>
        <div class="kpi-value">{{ lossEnergy }} kWh</div>
      </el-card>
      <el-card class="kpi-card">
        <div class="kpi-title">损失比例</div>
        <div class="kpi-value">{{ lossRate }}%</div>
      </el-card>
    </div>

    <!-- 桑基图 -->
    <div class="sankey-section">
      <el-card class="chart-card">
        <div class="chart-header">能源流向分析</div>
        <div ref="sankeyRef" class="sankey-chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import * as echarts from "echarts";
import { getflowAnalysis } from "@/api/stat/home";
import { ElMessage } from "element-plus";

// 顶部筛选
const granularity = ref("day");
const pickedDate = ref("");
const energyType = ref(20); // 默认选择电

const datePickerType = computed(() =>
  granularity.value === "day"
    ? "date"
    : granularity.value === "month"
    ? "month"
    : "year"
);
const dateFormat = computed(() =>
  granularity.value === "day"
    ? "YYYY-MM-DD"
    : granularity.value === "month"
    ? "YYYY-MM"
    : "YYYY"
);
const valueFormat = dateFormat;

async function handleSearch() {
  if (!pickedDate.value) {
    ElMessage.warning("请选择日期");
    return;
  }
  
  try {
    const params = {
      statTime: pickedDate.value,
      energyType: energyType.value
    };
    
    console.log("调用能源流向分析接口参数:", params);
    const response = await getflowAnalysis(params);
    console.log("接口返回数据:", response);
    
    // 处理接口返回的数据
    if (response.data) {
      processApiData(response.data);
    } else {
      ElMessage.warning("暂无数据");
      renderSankey(); // 使用模拟数据
    }
  } catch (error) {
    console.error("获取能源流向分析数据失败:", error);
    ElMessage.error("获取数据失败，请重试");
    renderSankey(); // 出错时使用模拟数据
  }
}

// KPI 数据
const totalEnergy = ref("9904.8");
const subEnergy = ref("15159");
const lossEnergy = ref("-5254.2");
const lossRate = ref("-53.00");

// 处理接口返回的数据
function processApiData(data) {
  console.log("处理能源流向分析数据:", data);
  
  // 处理KPI数据 - 从flowDataVos中计算
  if (data.flowDataVos && Array.isArray(data.flowDataVos)) {
    // 收集所有节点，找出根节点和2级节点
    const allNodes = new Set();
    const sourceNodes = new Set();
    const targetNodes = new Set();
    
    data.flowDataVos.forEach(item => {
      if (item.source && item.source.trim()) {
        allNodes.add(item.source.trim());
        sourceNodes.add(item.source.trim());
      }
      if (item.target && item.target.trim()) {
        allNodes.add(item.target.trim());
        targetNodes.add(item.target.trim());
      }
    });
    
    // 找出根节点（只作为target，不作为source的节点）
    const rootNodes = new Set();
    allNodes.forEach(node => {
      if (!sourceNodes.has(node)) {
        rootNodes.add(node);
      }
    });
    
    // 找出2级节点（根节点的直接子节点）
    const secondLevelNodes = new Set();
    data.flowDataVos.forEach(item => {
      if (item.source && item.target && 
          rootNodes.has(item.source.trim()) && 
          !rootNodes.has(item.target.trim())) {
        secondLevelNodes.add(item.target.trim());
      }
    });
    
    console.log("所有节点:", Array.from(allNodes));
    console.log("根节点:", Array.from(rootNodes));
    console.log("2级节点:", Array.from(secondLevelNodes));
    
    // 计算累计能耗（根节点的能耗）
    let totalSum = 0; // 累计能耗：根节点的能耗
    rootNodes.forEach(rootNode => {
      data.flowDataVos.forEach(item => {
        if (item.target && item.target.trim() === rootNode) {
          totalSum += parseFloat(item.value) || 0;
        }
      });
    });
    
    // 计算分表能耗（2级节点的能耗总和）
    let subSum = 0; // 分表能耗：2级节点的能耗总和
    secondLevelNodes.forEach(secondNode => {
      data.flowDataVos.forEach(item => {
        if (item.target && item.target.trim() === secondNode) {
          subSum += parseFloat(item.value) || 0;
        }
      });
    });
    
    // 计算损失量和损失比例
    const loss = totalSum - subSum;
    const lossRateValue = totalSum > 0 ? (loss / totalSum * 100) : 0;
    
    totalEnergy.value = totalSum.toFixed(1);
    subEnergy.value = subSum.toFixed(1);
    lossEnergy.value = loss.toFixed(1);
    lossRate.value = lossRateValue.toFixed(2);
    
    console.log("KPI计算结果:", {
      totalSum,
      subSum,
      loss,
      lossRateValue,
      rootNodes: Array.from(rootNodes),
      secondLevelNodes: Array.from(secondLevelNodes)
    });
  }
  
  // 处理桑基图数据 - 使用flowDataVos
  if (data.flowDataVos && Array.isArray(data.flowDataVos)) {
    const { nodes, links } = processFlowData(data.flowDataVos);
    
    // 检查是否有有效的连接数据
    if (links.length > 0) {
      console.log("使用真实数据渲染桑基图");
      renderSankeyWithData(nodes, links);
    } else {
      console.log("真实数据无有效连接，使用模拟数据");
      renderSankey();
    }
  } else {
    console.log("没有flowDataVos数据，使用模拟数据");
    // 如果没有桑基图数据，使用模拟数据
    renderSankey();
  }
}

// 处理flowDataVos数据，转换为桑基图需要的格式
function processFlowData(flowDataVos) {
  console.log("处理flowDataVos数据:", flowDataVos);
  
  // 收集所有节点名称
  const nodeNames = new Set();
  flowDataVos.forEach(item => {
    // 添加所有非空的source和target
    if (item.source && item.source.trim()) {
      nodeNames.add(item.source.trim());
    }
    if (item.target && item.target.trim()) {
      nodeNames.add(item.target.trim());
    }
  });
  
  // 计算每个节点的累计能耗和线损率
  const nodeData = {};
  
  // 初始化所有节点
  Array.from(nodeNames).forEach(name => {
    nodeData[name] = {
      totalEnergy: 0,    // 累计能耗
      childrenEnergy: 0, // 子节点能耗总和
      lossRate: 0       // 线损率
    };
  });
  
  // 计算每个节点的累计能耗
  // 根据数据结构，每个节点的累计能耗应该是它作为target时接收到的所有value的总和
  flowDataVos.forEach(item => {
    if (item.target && item.target.trim()) {
      const targetName = item.target.trim();
      const value = parseFloat(item.value) || 0.1; // null值设为0.1
      nodeData[targetName].totalEnergy += value;
    }
  });
  
  // 计算每个节点的子节点能耗总和（作为source时输出的所有value）
  flowDataVos.forEach(item => {
    if (item.source && item.source.trim() && item.target && item.target.trim()) {
      const sourceName = item.source.trim();
      const value = parseFloat(item.value) || 0.1; // null值设为0.1
      
      // 累加子节点能耗
      nodeData[sourceName].childrenEnergy += value;
    }
  });
  
  // 计算线损率
  Object.keys(nodeData).forEach(nodeName => {
    const data = nodeData[nodeName];
    if (data.totalEnergy > 0) {
      // 如果没有子节点（childrenEnergy为0），线损率为0%
      // 如果有子节点，计算线损率 = (总能耗 - 子节点能耗) / 总能耗 * 100%
      if (data.childrenEnergy === 0) {
        data.lossRate = 0; // 叶子节点，线损率为0%
      } else {
        data.lossRate = ((data.totalEnergy - data.childrenEnergy) / data.totalEnergy * 100);
      }
    } else {
      data.lossRate = 0;
    }
  });
  
  console.log("节点数据计算:", nodeData);
  
  // 创建节点数组，包含累计能耗和线损率信息
  const nodes = Array.from(nodeNames).map(name => ({
    name: name,
    value: nodeData[name].totalEnergy,
    lossRate: nodeData[name].lossRate
  }));
  
  // 创建连接数组，显示占比
  const links = flowDataVos
    .filter(item => 
      item.source && item.source.trim() && // 必须有source
      item.target && item.target.trim() // 必须有target
    )
    .map(item => {
      const sourceName = item.source.trim();
      const targetName = item.target.trim();
      const value = parseFloat(item.value) || 0.1; // null值设为0.1
      const sourceTotalEnergy = nodeData[sourceName].totalEnergy;
      
      // 计算占比 - 基于父节点的总能耗
      const percentage = sourceTotalEnergy > 0 ? (value / sourceTotalEnergy * 100) : 0;
      
      return {
        source: sourceName,
        target: targetName,
        value: value,
        percentage: percentage.toFixed(1) + '%'
      };
    });
  
  console.log("转换后的节点数据:", nodes);
  console.log("转换后的连接数据:", links);
  
  return { nodes, links };
}

// 桑基图
const sankeyRef = ref(null);
let chart;

function getMockSankeyData() {
  // 简化的假数据：总表 -> 三个主变 -> 多个用电点
  const nodes = [
    { name: "总表" },
    { name: "1号主变" },
    { name: "2号主变" },
    { name: "3号主变" },
    { name: "龙门铣床CNC总" },
    { name: "装配车间" },
    { name: "800T高压铸造力柜" },
    { name: "冷却塔" },
    { name: "空压机" },
  ];

  const links = [
    { source: "总表", target: "1号主变", value: 5200 },
    { source: "总表", target: "2号主变", value: 3800 },
    { source: "总表", target: "3号主变", value: 4100 },

    { source: "1号主变", target: "龙门铣床CNC总", value: 2600 },
    { source: "1号主变", target: "装配车间", value: 1800 },
    { source: "1号主变", target: "冷却塔", value: 800 },

    { source: "2号主变", target: "装配车间", value: 1500 },
    { source: "2号主变", target: "800T高压铸造力柜", value: 1200 },
    { source: "2号主变", target: "空压机", value: 1100 },

    { source: "3号主变", target: "龙门铣床CNC总", value: 1400 },
    { source: "3号主变", target: "冷却塔", value: 900 },
    { source: "3号主变", target: "空压机", value: 1200 },
  ];
  return { nodes, links };
}

// 使用真实数据渲染桑基图
function renderSankeyWithData(nodes, links) {
  console.log("开始渲染桑基图，节点数:", nodes.length, "连接数:", links.length);
  
  if (!sankeyRef.value) {
    console.error("桑基图容器不存在");
    return;
  }
  
  if (chart) chart.dispose();
  chart = echarts.init(sankeyRef.value);
  
  console.log("ECharts实例创建成功");

  const option = {
    tooltip: { 
      trigger: "item",
      formatter: function(params) {
        if (params.dataType === 'node') {
          return `${params.data.name}<br/>累计能耗: ${params.data.value} kWh<br/>线损率: ${params.data.lossRate.toFixed(2)}%`;
        } else if (params.dataType === 'edge') {
          return `${params.data.source} → ${params.data.target}<br/>占比: ${params.data.percentage}<br/>能耗: ${params.data.value} kWh`;
        }
        return '';
      }
    },
    series: [
      {
        type: "sankey",
        nodeAlign: "left",
        emphasis: { focus: "adjacency" },
        data: nodes,
        links: links,
        lineStyle: {
          color: "source",
          curveness: 0.5,
          opacity: 0.6, // 增加透明度
        },
        itemStyle: {
          borderWidth: 1,
          borderColor: "#fff",
        },
        label: {
          color: "#2c3e50",
          fontSize: 12,
        },
        // 设置最小连接宽度
        minWidth: 1,
        minHeight: 1,
        color: [
          "#16A5B7",
          "#4fdaca",
          "#32b7cb",
          "#409EFF",
          "#67C23A",
          "#90CAF9",
        ],
      },
    ],
  };

  chart.setOption(option);
  console.log("桑基图配置设置完成");
  
  window.addEventListener("resize", () => chart && chart.resize());
}

// 使用模拟数据渲染桑基图
function renderSankey() {
  if (!sankeyRef.value) return;
  if (chart) chart.dispose();
  chart = echarts.init(sankeyRef.value);

  const { nodes, links } = getMockSankeyData();

  const option = {
    tooltip: { trigger: "item" },
    series: [
      {
        type: "sankey",
        nodeAlign: "left",
        emphasis: { focus: "adjacency" },
        data: nodes,
        links: links,
        lineStyle: {
          color: "source",
          curveness: 0.5,
          opacity: 0.4,
        },
        itemStyle: {
          borderWidth: 1,
          borderColor: "#fff",
        },
        label: {
          color: "#2c3e50",
          fontSize: 12,
        },
        color: [
          "#16A5B7",
          "#4fdaca",
          "#32b7cb",
          "#409EFF",
          "#67C23A",
          "#90CAF9",
        ],
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => chart && chart.resize());
}

onMounted(() => {
  // 默认今天
  const now = new Date();
  pickedDate.value = `${now.getFullYear()}-${String(
    now.getMonth() + 1
  ).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
  nextTick(() => {
    // 自动调用接口获取数据
    handleSearch();
  });
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 12px;
  background: #f1f2f5;
  height: 100%;
  overflow-y: auto;
}

.filter-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 12px 16px;
  margin-bottom: 12px;

  .filter-row {
    display: flex;
    align-items: center;
    gap: 12px;

    .granularity {
      :deep(.el-radio-group) {
        display: flex;
        gap: 8px;

        .el-radio-button__inner {
          border-radius: 6px;
          border: 1px solid #dcdfe6;
          background: #ffffff;
          color: #606266;
          padding: 6px 14px;
          font-weight: 500;

          &:hover {
            color: #16a5b7;
            border-color: #16a5b7;
          }
        }

        .el-radio-button__original-radio:checked + .el-radio-button__inner {
          background: linear-gradient(135deg, #16a5b7 0%, #138a9a 100%);
          border-color: #16a5b7;
          color: #fff;
          box-shadow: 0 2px 4px rgba(22, 165, 183, 0.3);
        }
      }
    }

    .date-picker,
    .energy-type {
      :deep(.el-input__wrapper),
      :deep(.el-select__wrapper) {
        border-radius: 6px;
        &:hover {
          border-color: #16a5b7;
        }
        &.is-focus,
        &.is-focused {
          border-color: #16a5b7;
          box-shadow: 0 0 0 2px rgba(22, 165, 183, 0.2);
        }
      }
    }

    :deep(.el-button.el-button--primary) {
      border-radius: 6px;
      background: linear-gradient(135deg, #16a5b7 0%, #138a9a 100%);
      border: none;
      &:hover {
        background: linear-gradient(135deg, #138a9a 0%, #0f6b7a 100%);
      }
    }
  }
}

.kpi-section {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-bottom: 12px;

  .kpi-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    :deep(.el-card__body) {
      padding: 16px;
    }

    .kpi-title {
      color: #909399;
      font-size: 12px;
      margin-bottom: 6px;
    }
    .kpi-value {
      color: #303133;
      font-size: 20px;
      font-weight: 700;
    }
  }
}

.sankey-section {
  height: 700px;
  .chart-card {
    border-radius: 8px;
    height: 100%;
  }
  .chart-header {

    padding: 12px 16px 0 16px;
    font-weight: 600;
    color: #2c3e50;
  }
  .sankey-chart {
    height: 560px;
    width: 100%;
  }
}
</style>
